/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.fedoraaccess.rest;

import cz.mzk.kramerius.commons.DatastreamId;
import cz.mzk.kramerius.fedoraaccess.FedoraServer;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public abstract class AddDatastreamByReferenceOperation extends AbstractOperation {

    private static final Logger logger = Logger.getLogger(AddDatastreamByReferenceOperation.class.getName());

    public AddDatastreamByReferenceOperation(FedoraServer fedoraServer) {
        super(new HttpConnector(fedoraServer, HttpMethod.POST));
    }

    boolean run(String pid, DatastreamId dsId, String url, String mimeType, String label) {
        String request = buildRequest(pid, dsId, url, mimeType, label);
        logger.log(Level.FINE, "request: ''{0}''", request);
        try {
            String result = connector.processRequestWithStringResult(request);
            logger.log(Level.FINE, "result: ''{0}''", result);
            return true;
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
            return false;
        }
    }

    private String buildRequest(String pid, DatastreamId dsId, String url, String mimeType, String label) {
        StringBuilder builder = new StringBuilder();
        builder.append(getBaseUrl());
        builder.append("/objects/").append(pid);
        builder.append("/datastreams/").append(dsId.toString());
        builder.append("?controlGroup=");
        builder.append(getControllGroup().getCode());
        builder.append("&dsLocation=").append(url);
        builder.append("&mimeType=").append(mimeType);
        if (label != null) {
            try {
                builder.append("&dsLabel=").append(URLEncoder.encode(label, "UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(AddExternallyReferencedDatastreamOperation.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return builder.toString();
    }

    abstract ControllGroup getControllGroup();
}
